package widgets

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/nanakura/imgui-restclient/db/model"
	g "github.com/AllenDang/giu"
)

func (app *MyApp) HistoryTabItem() *g.TabItemWidget {
	return g.TabItem("请求历史").Layout(
		g.Table().Columns(
			g.TableColumn("Request"),
			g.TableColumn("Response"),
			g.TableColumn("Date"),
			g.TableColumn("Time"),
			g.TableColumn("操作"),
		).Rows(
			func() (res []*g.TableRowWidget) {
				for i, h := range app.history {
					idx := i
					res = append(res, g.TableRow(
						g.Label(fmt.Sprintf("%s %s", h.Method, h.Url)).Wrapped(true),
						g.Label(h.Response).Wrapped(true),
						g.Label(h.Date.Format(time.DateTime)).Wrapped(true),
						g.Label(fmt.Sprintf("%vms", h.Time)),
						g.Row(
							g.Button("应用").OnClick(func() {
								app.lookingBackHistory(idx)
							}),
							g.Button("删除").OnClick(func() {
								app.removeHistoryByIdx(idx)
							}),
						),
					))
				}
				return
			}()...,
		),
	)
}

func (app *MyApp) removeHistoryByIdx(i int) {
	model.RemoveHistoryById(app.history[i].Id)
	app.history = append(app.history[:i], app.history[:i+1]...)
}

func (app *MyApp) lookingBackHistory(i int) {
	app.clearCurrentRequest()
	h := app.history[i]
	hmap := make(map[string]string)
	pmap := make(map[string]string)
	json.Unmarshal([]byte(h.Headers), &hmap)
	json.Unmarshal([]byte(h.Params), &pmap)
	app.url = h.Url
	for k, v := range hmap {
		app.headersPairs = append(app.headersPairs, Pair{K: k, V: v})
	}
	for k, v := range pmap {
		app.paramsPairs = append(app.paramsPairs, Pair{K: k, V: v})
	}
	app.reqBodyEditor.Text(h.Body)
	app.contentType = h.ContentType
}

func (app *MyApp) refreshHistory() {
	history, err := model.GetHistory()
	if err != nil {
		return
	}
	app.history = history
}
